import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:gim_plugin/gim_plugin.dart';
import 'package:gim_plugin_example/components/loading_box.dart';
import 'package:gim_plugin_example/components/my_img.dart';
import 'package:gim_plugin_example/config.dart';
import 'package:gim_plugin_example/consts.dart';
import 'package:gim_plugin_example/pages/pg_chat_room/msg_elem/msg_box.dart';
import 'package:gim_plugin_example/utils/cache.dart';
import 'package:video_player/video_player.dart';

import '../../../icons.dart';

class VdoMsg extends StatefulWidget {
  final C2cMsg msg;

  VdoMsg({Key? key, required this.msg}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _VdoMsgState();
}

class _VdoMsgState extends State<VdoMsg> {
  late VideoPlayerController controller;
  late Future<void> _initializeVideoPlayerFuture;
  late VideoMsg videoMsg;
  late String cover;
  bool playing = false;

  @override
  void initState() {
    videoMsg = VideoMsg.fromJson(json.decode(widget.msg.msgData!));
    if (videoMsg.url!.startsWith(ASSET_PREFIX)) {
      controller = VideoPlayerController.network(genCosUrl(videoMsg.url!));
    } else {
      controller = VideoPlayerController.file(File(videoMsg.url!));
    }
    controller.setLooping(false);
    controller.setVolume(0.5);
    _initializeVideoPlayerFuture = controller.initialize().then((value) {});
    controller.addListener(() {
      if (controller.value.isPlaying) {
        if (!playing) {
          setState(() {
            playing = true;
          });
        }
      } else {
        if (playing) {
          setState(() {
            playing = false;
          });
        }
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double maxSize = 140;
    double width = maxSize;
    double height = maxSize;
    double aspectRatio = videoMsg.width! / videoMsg.height!;
    if (aspectRatio > 1) {
      width = maxSize;
      height = maxSize / aspectRatio;
    } else if (aspectRatio < 1) {
      height = maxSize;
      width = height * aspectRatio;
    }
    return MsgBox(
        msg: widget.msg,
        padding: 0,
        bgColor: Colors.transparent,
        onTap: () {
          if (controller.value.isPlaying) {
            playing = false;
            controller.pause();
          } else {
            playing = true;
            controller.play();
          }
          setState(() {});
        },
        child: ClipRRect(
          borderRadius: widget.msg.fromUid == cache.getStringSync(UID)
              ? const BorderRadius.only(
                  topLeft: Radius.circular(10), bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10))
              : const BorderRadius.only(
                  topRight: Radius.circular(10), bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10)),
          child: SizedBox(
            width: width,
            height: height,
            child: FutureBuilder(
              future: _initializeVideoPlayerFuture,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  if (playing) {
                    return AspectRatio(
                      aspectRatio: double.parse('${videoMsg.width}') / double.parse('${videoMsg.height}'),
                      child: VideoPlayer(controller),
                    );
                  } else {
                    return LoadingBox(
                        myImg(
                          videoMsg.cover!,
                          width: width,
                          height: height,
                        ),
                        loadingIcon: iconVideoPlay(40));
                  }
                } else {
                  return LoadingBox(
                      myImg(
                        videoMsg.cover!,
                        width: width,
                        height: height,
                      ),
                      loadingIcon: iconVideoPlay(40));
                }
              },
            ),
          ),
        ));
  }
}
